package org.hy.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.apache.ibatis.jdbc.ScriptRunner;

public class DatabaseRunner {
	
	public static String Prefix_Dir = "target/classes/";
	public static String Conf_Database = "properties/database.properties";
	
	/**
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		String type = "mysql";
		buildDatabase(type);
	}

	public static void buildDatabase(String type) throws Exception{
		
		System.out.println("-------------------迁移数据库------------------------");
		Properties property = new Properties();
		//System.out.println(new File("").getAbsolutePath());
		final String confDatabasePath = Prefix_Dir  + Conf_Database;
		property.load(new FileInputStream(confDatabasePath));
		String driver,url,username,password;
		driver = property.getProperty("driver");
		url = property.getProperty("murl");
		if(url==null)url=property.getProperty("url");
		username = property.getProperty("username");
		password = property.getProperty("password");
		Class.forName(driver);
		Connection conn = DriverManager.getConnection(url, username, password);
		ScriptRunner sr = new ScriptRunner(conn);
		final String schemaPath,dataPath;
		schemaPath = Prefix_Dir + "/ddl/" + type + "/hy-schema.sql";
		dataPath = Prefix_Dir + "/ddl/" + type + "/hy-dataload.sql";
		sr.runScript(new FileReader(schemaPath));
		sr.runScript(new FileReader(dataPath));
		conn.commit();
		System.out.println("-------------------迁移数据库完成------------------------");
	}
}
